import { getEntireDepartments, getEntireMenus, getEntireRoles } from '@/services/main/main'
import type {
  IDepartmentList,
  IDepartmentResponse,
  IMenuListResponse,
  IMeunItem,
  IRoleList,
  IRoleResponse
} from '@/services/main/type'
import { defineStore } from 'pinia'
import type { IMain } from './type'

const useMainStore = defineStore('main', {
  state: (): IMain => ({
    entireRoles: [],
    entireDepartments: [],
    entireMenus: []
  }),
  actions: {
    async fetchEntireDataAction() {
      try {
        // 角色列表数据
        const rolesResult: IRoleResponse = await getEntireRoles()
        // 部门列表数据
        const departmentResult: IDepartmentResponse = await getEntireDepartments()
        // 菜单列表数据
        const menulistResult: IMenuListResponse = await getEntireMenus()
        if (rolesResult.code == 0) {
          this.entireRoles = rolesResult.data?.list as Array<IRoleList>
        } else {
          return Promise.reject(new Error('获取用户角色失败'))
        }

        if (departmentResult.code == 0) {
          this.entireDepartments = departmentResult.data?.list as Array<IDepartmentList>
        } else {
          return Promise.reject(new Error('获取用户部门数据失败'))
        }

        if (menulistResult.code === 0) {
          this.entireMenus = menulistResult.data?.list as Array<IMeunItem>
        } else {
          return Promise.reject(new Error('获取用户菜单数据失败'))
        }
      } catch (error) {
        return Promise.reject(new Error('获取用户角色失败或获取用户部门数据失败'))
      }
    }
  }
})

export default useMainStore
